/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.photobattle;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.widget.ProfilePictureView;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Fragment that represents the main selection screen for Scrumptious.
 */
public class Fragment_Best extends SherlockFragment 
{
	
	public static Fragment_Best m_Inst;
	 
    private ListView m_ListViewWorld;
    private List<Element_BestList> m_ListElementsWorld;

    private ListView m_ListViewCountry;
    private List<Element_BestList> m_ListElementsCountry;
    
    private ListView m_ListViewCity;
    private List<Element_BestList> m_ListElementsCity;
    
    private ListView m_ListViewFriends;
    private List<Element_BestList> m_ListElementsFriends;
    
    private TextView m_TxtWorld;
    private TextView m_TxtCountry;
    private TextView m_TxtCity;
    private TextView m_TxtFriend;
    private TextView m_TxtLoading;
    private LinearLayout m_FrameListViews;
    
    private final int QUERY_TYPE_WORLD = 0;
    private final int QUERY_TYPE_COUNTRY = 1;
    private final int QUERY_TYPE_CITY = 2;
    private final int QUERY_TYPE_FRIEND = 3;
    private final int QUERY_TYPE_TOTAL = QUERY_TYPE_FRIEND + 1;
    private static boolean m_IsAlreadyQueryed = false; 
    private Timer m_Timer = null;
    
    
    public static Fragment_Best Instace()
    {
    	if(m_Inst == null)
    		m_Inst = new Fragment_Best();
    		
    	return m_Inst;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);    
        
    }

    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
    	Log.i("game", "BestFragment on create");
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.bestplayers, container, false);
       
        m_ListViewWorld = (ListView) view.findViewById(R.id.ListBestWorld);
        m_ListViewCountry = (ListView) view.findViewById(R.id.ListBestCountry);
        m_ListViewCity = (ListView) view.findViewById(R.id.ListBestCity);
        m_ListViewFriends = (ListView) view.findViewById(R.id.ListBestFriend);       
        
        m_TxtWorld = (TextView) view.findViewById(R.id.txtWorld);
        m_TxtCountry = (TextView) view.findViewById(R.id.txtCountry);
        m_TxtCity = (TextView) view.findViewById(R.id.txtCity);
        m_TxtFriend = (TextView) view.findViewById(R.id.txtFriends);
        m_TxtLoading = (TextView) view.findViewById(R.id.txtLoading);
        m_FrameListViews = (LinearLayout) view.findViewById(R.id.FrameListViews);
        
        if(m_FrameListViews != null)
        {	
        	m_FrameListViews.setVisibility(View.GONE);
        }
        
        return view;
    }
    
    public void GetBestListAfterGettingFrdList()
    {
    	if(m_IsAlreadyQueryed == false && m_Timer == null)
        {
		    final Handler handler = new Handler();
		    m_Timer = new Timer(false);
		    TimerTask timerTask = new TimerTask() 
		    {
		        @Override
		        public void run() {
		            handler.post(new Runnable() 
		            {
		                @Override
		                public void run() 
		                {
		                   Tick();                    		
		                }
		            });
		        }
		    };
		    m_Timer.scheduleAtFixedRate(timerTask, 0, 1000);
        }
    }
    
    private void Tick()
    {
    	Log.i("game","------------------------$$$----------------------");
    	
    	PhotoBattleApplication app = PhotoBattleApplication.Instance();
    	boolean IsAlreadyInitFrdList = app.GetIsAlreadyInitFrdUIDs();
    	
    	if(m_IsAlreadyQueryed == false && IsAlreadyInitFrdList )
        {
    		m_Timer.cancel();
        	m_Timer = null;
        	m_IsAlreadyQueryed = true;
        	
        	for(int i = 0; i < QUERY_TYPE_TOTAL; i++)
        		GetBestList(i);
        	
        	
        }
    }

   

    private class BestListAdapter extends ArrayAdapter<Element_BestList> 
    {
        private List<Element_BestList> listElements;

        public BestListAdapter(Context context, int resourceId, List<Element_BestList> listElements) 
        {
            super(context, resourceId, listElements);
            
            this.listElements = listElements;
            for (int i = 0; i < listElements.size(); i++) 
            {
                listElements.get(i).setAdapter(this);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            View view = convertView;
            if (view == null) 
            {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.bestlistitem, null);
            }

            Element_BestList listElement = listElements.get(position);
            if (listElement != null) 
            {      
            	
            	ProfilePictureView ProfilePic = (ProfilePictureView) view.findViewById(R.id.profilepic);
                TextView textName = (TextView) view.findViewById(R.id.txtName);
                TextView textLevel = (TextView) view.findViewById(R.id.txtLevel);
                TextView textTitle = (TextView) view.findViewById(R.id.txtTitle);
                TextView textBattle = (TextView) view.findViewById(R.id.txtBattles);              
                
                
                listElement.SetViewElements(ProfilePic, textName, textTitle, textLevel, textBattle);
            }
            return view;
        }

    }
    
    
    private void GetBestList(final int QueryType)
    {      	
    	ParseQuery<ParseUser> Q1 = ParseUser.getQuery();
    	
    	if(QueryType == QUERY_TYPE_COUNTRY)
    	{
    		if(ParseUser.getCurrentUser() == null)
        		return;
    		
    		String Country = ParseUser.getCurrentUser().getString("Country");
    		if(Country.isEmpty())
        		return;
    		
    		Q1.whereEqualTo("Country", Country);
    		if(m_TxtCountry != null)
    			m_TxtCountry.setText("Best players in " + Country);
    	}
    	
    	else if(QueryType == QUERY_TYPE_CITY)
    	{
    		if(ParseUser.getCurrentUser() == null)
        		return;
    		
    		String City = ParseUser.getCurrentUser().getString("City");
    		if(City.isEmpty())
        		return;    		
    		
    		Q1.whereEqualTo("City", City);
    		if(m_TxtCity != null)
    			m_TxtCity.setText("Best players in " + City);
    	}
    	
    	else if(QueryType == QUERY_TYPE_FRIEND)
    	{
    		PhotoBattleApplication app = PhotoBattleApplication.Instance();
    		String[] FBIDs = app.GetAppFrdList();
    		if(FBIDs == null)
    			return;
    		Q1.whereContainedIn("FBID", Arrays.asList(FBIDs));
    	}
    	
    	Q1.orderByDescending("Points");
    	Q1.setLimit(5);    			
    	
    	
    	
    	Q1.findInBackground(new FindCallback<ParseUser>() 
    	{
    	  
    	  public void done(List<ParseUser> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)    		  
    		  {
    			  	if(m_TxtLoading != null)
    			  		m_TxtLoading.setVisibility(View.GONE);
    			  	
    			  	 if(m_FrameListViews != null)
    			        {	
    			        	m_FrameListViews.setVisibility(View.VISIBLE);
    			        }
    		  	    		  
    			  	if(QueryType == QUERY_TYPE_WORLD)	  	        	
    				  m_ListElementsWorld = new ArrayList<Element_BestList>();
    			  	
	  	        	else if(QueryType == QUERY_TYPE_COUNTRY)	  	        	
	  	        		m_ListElementsCountry = new ArrayList<Element_BestList>();
	  	        	
	  	        	else if(QueryType == QUERY_TYPE_CITY)	  	        	
	  	        		m_ListElementsCity = new ArrayList<Element_BestList>();
	  	        	
	  	        	else if(QueryType == QUERY_TYPE_FRIEND)	  	        	
	  	        		m_ListElementsFriends = new ArrayList<Element_BestList>();
	  	        	
	    	          	        
	    	        
	    	        //  Add Player's Battle First
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseUser Obj = results.get(i);	    	
	    	        	
	    	        	if(QueryType == QUERY_TYPE_WORLD)	  	        	
	    	        		AddToListElements(Obj, m_ListElementsWorld);
	      			  	
	  	  	        	else if(QueryType == QUERY_TYPE_COUNTRY)	  	        	
	  	  	        		AddToListElements(Obj, m_ListElementsCountry);
	  	  	        	
	  	  	        	else if(QueryType == QUERY_TYPE_CITY)	  	        	
	  	  	        		AddToListElements(Obj, m_ListElementsCity);
	  	  	        	
	  	  	        	else if(QueryType == QUERY_TYPE_FRIEND)	  	        	
	  	  	        	AddToListElements(Obj, m_ListElementsFriends);
	    	        	
	    	        	
	    	        }	   	        
	    	        	        
	
	    	        if(getActivity() != null )
	    	        {
	    	        	if(QueryType == QUERY_TYPE_WORLD)
	    	        	{
	    	        		m_ListViewWorld.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestWorld, m_ListElementsWorld));	    	        		
	    	        	}
	    	        	else if(QueryType == QUERY_TYPE_COUNTRY)
	    	        	{
	    	        		m_ListViewCountry.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestCountry, m_ListElementsCountry));	    	        		
	    	        	}
	    	        	else if(QueryType == QUERY_TYPE_CITY)
	    	        	{
	    	        		m_ListViewCity.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestCity, m_ListElementsCity));
	    	        	}
	    	        	else if(QueryType == QUERY_TYPE_FRIEND)
	    	        	{
	    	        		m_ListViewFriends.setAdapter(new BestListAdapter(getActivity(), R.id.ListBestFriend, m_ListElementsFriends));
	    	        	}
	    	        }
	    	        
	    	       
    		  }
    	  }
    	});
    	
    }
    
    private void AddToListElements(ParseUser Pobj,List<Element_BestList> LE )
    {
    	PhotoBattleApplication app = PhotoBattleApplication.Instance();
    	String Title = app.GetPlayerTitle();
    	int Level = Pobj.getInt("LevelNum");
    	
    	LE.add( new Element_BestList(
    								getActivity(), 
    								Pobj.getString("FBID"), 
    								Pobj.getUsername(), 
    								Title, 
    								Level, 
    								Pobj.getInt("TotalBattle"), 
    								Pobj.getInt("BattleWin")
    								)
    			);    	
		
    }
    
    //@Override
   // public void onDestroy() 
   // {
    	// TODO Auto-generated method stub
    	//super.onDestroy();
   // }
    
}
